package com.pat.web.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.NoNeedLogon;
import com.pat.web.model.AnswerComment;
import com.pat.web.model.AnswerCommentInfo;
import com.pat.web.model.AnswerInfo;
import com.pat.web.model.Focus;
import com.pat.web.model.QuestionInfo;

public class QuestionController extends Controller{
	private static final int PAGESIZE = 20;

	@NoNeedLogon
	public void getAnswerInfoList(){
		Integer pageIndex = getParaToInt("pageIndex");
		if (pageIndex == null || pageIndex < 1) {
			pageIndex = 1;
		}
		Integer pageSize = getParaToInt("pageSize");
		if (pageSize == null) {
			pageSize = PAGESIZE;
		}
		
		String selectSql = "select a.id,a.content,a.user_id,u.nick_name,u.photo,a.agree_num,a.disagree_num,a.collection_num,a.comment_num,a.create_time,a.update_time,a.question_id,q.title,q.answer_num ";
		String sqlExceptSelect ="from answer_info a ,question_info q ,user u where a.question_id = q.id and u.id = a.user_id  order by a.create_time desc";
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		
		Page<Record> records =  Db.paginate(pageIndex, pageSize,selectSql,sqlExceptSelect);
		response.setData(records);
		render(new JsonRender(response));
	}
	
	public void createQuestion() {
		QuestionInfo questionInfo = getBean(QuestionInfo.class, "");
		questionInfo.setUserId(getAttr(Constants.LOGIN_USER_ID));
		questionInfo.setCreateTime(new Date()).save();
		ApiResponse response = new ApiResponse();
		response.setData(questionInfo.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}
	
	public void updateQuestion() {
		QuestionInfo questionInfo = getBean(QuestionInfo.class, "");
		questionInfo.setUserId(getAttr(Constants.LOGIN_USER_ID));
		questionInfo.setUpdateTime(new Date()).update();
		ApiResponse response = new ApiResponse();
		response.setData(questionInfo.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}
	
	public void createAnswer() {
		AnswerInfo answerInfo = getBean(AnswerInfo.class, "");
		answerInfo.setUserId(getAttr(Constants.LOGIN_USER_ID));
		answerInfo.setCreateTime(new Date());
		if (answerInfo.save()) {
			QuestionInfo questionInfo = QuestionInfo.dao.findById(answerInfo.getQuestionId());
			if (questionInfo != null ) {
				questionInfo.setAnswerNum(questionInfo.getAnswerNum() + 1);
				questionInfo.setUpdateTime(new Date());
				questionInfo.update();
			}
		}
		ApiResponse response = new ApiResponse();
		response.setData(answerInfo.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}
	
	public void updateAnswer() {
		AnswerInfo answerInfo = getBean(AnswerInfo.class, "");
		answerInfo.setUpdateTime(new Date()).update();
		ApiResponse response = new ApiResponse();
		response.setData(answerInfo.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}
	
	@NoNeedLogon
	public void  getAnswerDetailById(){
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		Record record =Db.findFirst("select a.*,u.nick_name,u.photo,q.title from answer_info a ,user u ,question_info q  where a.user_id  = u.id and a.question_id = q.id and a.id = ? ", getParaToInt("id"));
		
		if (record != null) {
			Long userId = getAttr(Constants.LOGIN_USER_ID);
			if (userId != null && userId.equals(record.getLong("user_id"))) {
				record.set("editable", true);
				//查询收藏状态
				Record collectionStstus =Db.findFirst("select f.focus_content_id from answer_info a , focus f  where a.id = f.focus_content_id and f.focus_type = 4 and f.user_id = ? and a.id =? ",  userId,getParaToInt("id"));
				if (collectionStstus != null) {
					record.set("isCollected", true);
				}else{
					record.set("isCollected", false);
				}
			}else{
				record.set("editable", false);
			}
			List<Record> comments =Db.find("select a.*,u.nick_name,u.photo from answer_comment_info a ,user u  where a.user_id  = u.id and answer_id = ? ", getParaToInt("id"));
			if (comments != null) {
				record.set("comments", comments);
			}
		}
		response.setData(record);
		render(new JsonRender(response));
	}
	
	@NoNeedLogon
	public void  getQuestionDetailById(){
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		QuestionInfo record = QuestionInfo.dao.findFirst("select a.* ,f.focus_content_id from question_info  a left join focus f on  a.id = f.focus_content_id and f.focus_type = 3 and f.user_id = ? where a.id =?",  userId,getParaToInt("id"));
		if(record != null){
			if (userId != null && userId.equals(record.getUserId()) ) {
				record.put("editable", true);
			}else{
				record.put("editable", false);
			}
			
			List<Record> answerList = Db.find("select a.id,a.content,a.user_id,u.nick_name,a.agree_num,a.disagree_num,a.collection_num,a.create_time,a.update_time,a.question_id "
					+ " from answer_info a  ,user u "
					+ " where a.question_id = ? and u.id = a.user_id  order by a.create_time desc", getParaToInt("id"));
			record.put("answerList", answerList);
			record.put("answerNum", answerList == null ? 0 : answerList.size());
		}
		response.setData(record);
		render(new JsonRender(response));
	}
	
	public void focus() {	
		Long userId =  getAttr(Constants.LOGIN_USER_ID);
		Integer operateType = getParaToInt("operateType");
		Focus focus = getBean(Focus.class, "");
		Focus record = Focus.dao.findFirst("select * from focus where focus_type = ? and user_id = ? and focus_content_id = ? ", focus.getFocusType(),userId,focus.getFocusContentId());
		ApiResponse response = new ApiResponse();

		if (record != null ) {
			if(operateType != null && operateType == 1){
				response.setStatusCode("00001");
				response.setErrorMessage("已经收藏过了");
				renderJson(response);
			}else{
				if(record.delete()){
					if (focus.getFocusType() == 3) {
						QuestionInfo questionInfo = QuestionInfo.dao.findById(focus.getFocusContentId());
						if (questionInfo != null) {
							questionInfo.setUpdateTime(new Date());
							questionInfo.setCollectionNum(questionInfo.getCollectionNum() -1);
							questionInfo.update();
							response.setStatusCode("0000");
							response.setData(questionInfo.getCollectionNum());
							renderJson(response);
						}
					}else if (focus.getFocusType() == 4) {
						AnswerInfo answerInfo = AnswerInfo.dao.findById(focus.getFocusContentId());
						if (answerInfo != null) {
							answerInfo.setUpdateTime(new Date());
							answerInfo.setCollectionNum(answerInfo.getCollectionNum() - 1);
							answerInfo.update();
							response.setStatusCode("0000");
							response.setData(answerInfo.getCollectionNum());
							renderJson(response);
						}
					}
				}else{
					response.setStatusCode("00003");
					response.setErrorMessage("取消收藏失败 ");
					renderJson(response);
				}
			}
		}else{
			if(operateType != null && operateType == 1){
				focus.setUserId(userId);
				focus.setCreateTime(new Date());
				focus.setStatus(1L);

				if (focus.save()) {
					if (focus.getFocusType() == 3) {
						QuestionInfo questionInfo = QuestionInfo.dao.findById(focus.getFocusContentId());
						if (questionInfo != null) {
							questionInfo.setUpdateTime(new Date());
							questionInfo.setCollectionNum(questionInfo.getCollectionNum() + 1);
							questionInfo.update();
							response.setData(questionInfo.getCollectionNum());
						}
					}else if (focus.getFocusType() == 4) {
						AnswerInfo answerInfo = AnswerInfo.dao.findById(focus.getFocusContentId());
						if (answerInfo != null) {
							answerInfo.setUpdateTime(new Date());
							answerInfo.setCollectionNum(answerInfo.getCollectionNum() + 1);
							answerInfo.update();
							response.setData(answerInfo.getCollectionNum());
						}
					}
					
				}
				response.setStatusCode("0000");
				renderJson(response);
			}else {
				response.setStatusCode("00004");
				response.setErrorMessage("取消收藏失败 ");
			}
		}
	}
 
	public void makeCommentsForAnswer() {
		Long userId =  getAttr(Constants.LOGIN_USER_ID);
		Long answerId = getParaToLong("answerId");
		AnswerComment answerComment = AnswerComment.dao.findFirst("select * from answer_comment where user_id = ? and answer_id = ? ", userId,answerId);
		Long agreeStatus = getParaToLong("agreeStatus");
		String commentContent = getPara("commentContent");
		AnswerInfo answerInfo = AnswerInfo.dao.findById(answerId);
		
		
		ApiResponse response = new ApiResponse();
		
		if (answerInfo == null) {
			response.setErrorMessage("无法根据id查询到对应的回答");
			response.setStatusCode("00001");
			renderJson(response);
		}
		
		answerInfo.setUpdateTime(new Date());

		if (answerComment == null) {//不存在，则创建评价
			answerComment = getBean(AnswerComment.class,"");
			answerComment.setCreateTime(new Date());
			answerComment.setUserId(userId);
			if (agreeStatus != null) {
				answerComment.setAgreeStatus(agreeStatus);
			}
			answerComment.save();
			
			if (agreeStatus != null) {
				if (agreeStatus == 1) {
					answerInfo.setAgreeNum(answerInfo.getAgreeNum() + 1);
				}
				
				if (agreeStatus == 2) {
					answerInfo.setDisagreeNum(answerInfo.getDisagreeNum() + 1);
				}
			}
			
			if (StringUtils.isNotBlank(commentContent)) {
				answerInfo.setCommentNum(answerInfo.getCommentNum() + 1);
				
				AnswerCommentInfo answerCommentInfo = getBean(AnswerCommentInfo.class,"");
				answerCommentInfo.setCreateTime(new Date());
				answerCommentInfo.setUserId(userId);
				answerCommentInfo.setAnswerId(answerId);
				answerCommentInfo.setCommentDatail(commentContent);
				answerCommentInfo.save();
			}			
		}else{
			if(agreeStatus != null){
				Long status = answerComment.getAgreeStatus();
				if (status != null) {
					if (agreeStatus == 2) {
						if (status == 1) {
							answerInfo.setAgreeNum(answerInfo.getAgreeNum() - 1);
						}
						answerInfo.setDisagreeNum(answerInfo.getDisagreeNum() + 1);
						answerComment.setAgreeStatus(agreeStatus);
					}
					
					if (agreeStatus == 1) {
						answerInfo.setAgreeNum(answerInfo.getAgreeNum() + 1);
						if (status == 2) {
							answerInfo.setDisagreeNum(answerInfo.getDisagreeNum() - 1);
						}
						answerComment.setAgreeStatus(agreeStatus);
					}
				}
			}
			
			if (StringUtils.isNotBlank(commentContent)) {
				answerInfo.setCommentNum(answerInfo.getCommentNum() + 1);
				
				AnswerCommentInfo answerCommentInfo = getBean(AnswerCommentInfo.class,"");
				answerCommentInfo.setCreateTime(new Date());
				answerCommentInfo.setUserId(userId);
				answerCommentInfo.setAnswerId(answerId);
				answerCommentInfo.setCommentDatail(commentContent);
				answerCommentInfo.save();
			}
			
			answerComment.setUpdateTime(new Date());
			answerComment.update();

		}
		
		answerInfo.update();
		
		response.setData(answerInfo);
		response.setStatusCode("0000");
		renderJson(response);
	}
	
	@NoNeedLogon
	public void  getQuestionList(){
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		Integer sortType = getParaToInt("sortType");
		String sql = null;
		if (sortType != null && sortType == 1) {
			sql = "select * from question_info order by (collection_num + answer_num) desc" ;
		}else{
			sql = "select * from question_info order by create_time desc" ;
		}
		List<QuestionInfo> questionInfos = QuestionInfo.dao.find(sql);
		response.setData(questionInfos);
		render(new JsonRender(response));
	}

	@NoNeedLogon
	public void  getQuestionListByKeyWord(){
		Integer pageIndex = getParaToInt("pageIndex");
		if (pageIndex == null || pageIndex < 1) {
			pageIndex = 1;
		}
		Integer pageSize = getParaToInt("pageSize");
		if (pageSize == null) {
			pageSize = PAGESIZE;
		}
		
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		String keyWord = getPara("keyWord");
		if (keyWord == null) {
			render(new JsonRender(response));
			return ;
		}
		
		String selectSql = "select a.id answerId,a.content,a.user_id,u.nick_name,u.photo,a.agree_num,a.disagree_num,a.collection_num,a.comment_num,a.create_time,a.update_time,q.title,q.description,q.answer_num,q.id questionId,q.collection_num questionCollectionNum ";
		String sqlExceptSelect ="from ( question_info q left join answer_info a  on a.question_id = q.id ) left join user u  on u.id = a.user_id where   "
				+ "  (q.title like '%" + keyWord + "%' or a.content like '%" + keyWord + "%') "
				+ " order by a.create_time desc";
		
		
		Page<Record> records =  Db.paginate(pageIndex, pageSize,selectSql,sqlExceptSelect);
		response.setData(records);
		render(new JsonRender(response));
	}

	
}
